package cn.iocoder.yudao.module.energy.service.data;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.energy.controller.admin.data.vo.*;
import cn.iocoder.yudao.module.energy.dal.dataobject.data.DataDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.energy.dal.mysql.data.DataMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.energy.enums.ErrorCodeConstants.*;

/**
 * 能耗数据 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DataServiceImpl implements DataService {

    @Resource
    private DataMapper dataMapper;

    @Override
    public Long createData(DataSaveReqVO createReqVO) {
        // 插入
        DataDO data = BeanUtils.toBean(createReqVO, DataDO.class);
        System.out.println("现在service的电流是"+data.getCurrents());
        dataMapper.insert(data);
        // 返回
        return data.getId();
    }

    @Override
    public void updateData(DataSaveReqVO updateReqVO) {
        // 校验存在
        validateDataExists(updateReqVO.getId());
        // 更新
        DataDO updateObj = BeanUtils.toBean(updateReqVO, DataDO.class);
        dataMapper.updateById(updateObj);
    }

    @Override
    public void deleteData(Long id) {
        // 校验存在
        validateDataExists(id);
        // 删除
        dataMapper.deleteById(id);
    }

    private void validateDataExists(Long id) {
        if (dataMapper.selectById(id) == null) {
            throw exception(DATA_NOT_EXISTS);
        }
    }

    @Override
    public DataDO getData(Long id) {
        return dataMapper.selectById(id);
    }

    @Override
    public PageResult<DataDO> getDataPage(DataPageReqVO pageReqVO) {
        return dataMapper.selectPage(pageReqVO);
    }
    
    @Override
    public List<Map<String, Object>> listDevices() {
        // 查询所有数据
        List<DataDO> dataList = dataMapper.selectList();
        
        // 使用Map存储设备信息，key为设备ID，避免重复
        Map<String, Map<String, Object>> deviceMap = new HashMap<>();
        
        // 遍历数据，按设备ID分组
        for (DataDO data : dataList) {
            if (data.getDeviceId() != null && data.getDeviceName() != null) {
                Map<String, Object> deviceInfo = new HashMap<>();
                deviceInfo.put("deviceId", data.getDeviceId());
                deviceInfo.put("deviceName", data.getDeviceName());
                deviceMap.put(data.getDeviceId(), deviceInfo);
            }
        }
        
        // 转换为List返回
        return new ArrayList<>(deviceMap.values());
    }
}